package com.ohy.tencent.config;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.*;

/**
 * @description:
 * @author: ouhy
 * @create: 2020-11-26 13:55:48
 **/

@Slf4j
@Configuration
public class LibFileInit {

    @Bean
    public LibFileInit FfdynsourceInit() throws IOException {

        String loadLibDir = FileUtil.isWindows() ? "/tool/ffmpeg-win64-v4.2.2.exe" : "/tool/ffmpeg-linux64-v4.1";
        String outLibDir = FileUtil.isWindows() ? "C:\\ProgramData\\Tencent\\ffmpeg\\" : "/opt/video/ffmpeg/";

        copyFile(new String[]{loadLibDir}, outLibDir);
        log.info("=====================this lib file init ok!");


        return new LibFileInit();
    }

    // 拷贝文件 flag
    public void copyFile(String[] fPaths, String outPath) throws IOException {
        for (String path : fPaths) {
            ResourceLoader resourceLoader = new DefaultResourceLoader();
            Resource resource = resourceLoader.getResource("classpath:" + path);
            if (resource.exists()) {
                InputStream is = resource.getInputStream();

                File pathF = new File(outPath);
                if (!pathF.exists()) {
                    pathF.mkdirs();
                }
                File f = new File(outPath, path.substring(path.lastIndexOf("/"), path.length()));
                log.info("create file path 文件路径：{}", f.getAbsolutePath());
                if (f.exists()) {
                    f.delete();
                }

                f.createNewFile();
                f.setReadable(true);
                f.setWritable(true);
                f.setExecutable(true);
                BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(f, false));
                int lentgh = 0;
                while ((lentgh = is.read()) != -1) {
                    os.write(lentgh);
                }

                is.close();
                os.close();
            }

        }

        //如果是centos
        if (!FileUtil.isWindows()) {
            String outLibDir = FileUtil.isWindows() ? "C:\\ProgramData\\Tencent\\ffmpeg\\" : "/opt/video/ffmpeg/";
            String ffmpegPath = outLibDir + (FileUtil.isWindows() ? "ffmpeg-win64-v4.2.2.exe" : "ffmpeg-linux64-v4.1");
            String command = "chmod 777 " + ffmpegPath;
            Runtime.getRuntime().exec(command);
            log.info("赋值777权限,ffmpegPath:{}", ffmpegPath);
        }

    }


}